<template>
  <div>
    <n-card
        :header-style="{padding: '5px 5px 5px 10px'}" :content-style="{padding: '5px 5px 5px 5px'}"
        title="音频选择"
        :segmented="{
            content: true,
            footer: 'soft'
          }">
      <template #header-extra>
        <n-button type="primary" @click="modalShow = true" size="small">选择音频</n-button>
        <n-button type="warning" @click="removeAudioFile" style="margin-left: 5px" size="small">删除</n-button>
      </template>
      <audio
          v-if="audioFileId"
          ref="audioPlayer"
          controls
          style="width: 100%;margin-top: 10px"
          :src=fileFunction.getViewFilePathByUserFileId(audioFileId)
      >
      </audio>
      <n-space justify="center">
        <n-empty description="未选择音频" v-if="!audioFileId">
        </n-empty>
      </n-space>
    </n-card>

    <n-card
      style="margin-top: 5px;"
      :header-style="{padding: '5px 5px 5px 10px'}" :content-style="{padding: '5px 5px 5px 5px'}"
      title="时间轴校准"
          :segmented="{
          content: true,
          footer: 'soft'
        }">

      <n-grid x-gap="10">
        <n-grid-item span="16">
          <n-h6>分镜信息</n-h6>
          <n-table  :single-line="false">
            <tbody>
            <tr>
              <td style="width: 30px">1</td>
              <td>反常的</td>
              <td>
                <div class="card1 w-64 flex justify-center px-5">
                  <VueDraggableNext
                      class="dragArea list-group w-full"
                      :list="list3"
                      :group="{ name: 'people' }"
                      :sort="true"
                      @change="log"
                      :move="checkMove"
                  >
                    <div
                        class="list-group-item bg-gray-300 m-1 p-3 rounded-md text-center"
                        v-for="element in list3"
                        :key="element.name"
                    >
                      {{ element.name }}
                    </div>
                  </VueDraggableNext>
                </div>

              </td>
            </tr>
            <tr>
              <td>放弃</td>
              <td>反常的</td>
              <td>
                <div class="card1 w-64 flex justify-center px-5">
                  <VueDraggableNext
                      class="dragArea list-group w-full"
                      :list="list1"
                      :group="{ name: 'people'  }"
                      :sort="true"
                      @change="log"
                      :move="checkMove"
                  >
                    <div
                        class="list-group-item bg-gray-300 m-1 p-3 rounded-md text-center"
                        v-for="element in list1"
                        :key="element.name"
                    >
                      {{ element.name }}
                    </div>
                  </VueDraggableNext>
                </div>

              </td>
            </tr>
            </tbody>
          </n-table>
        </n-grid-item>
        <n-grid-item span="8">
          <n-h6>字幕信息</n-h6>
          <n-ul>
            <VueDraggableNext
                class="dragArea list-group w-full"
                :list="list2"
                :group="{ name: 'people'  }"
                :sort="true"
                @change="log"
                :move="checkMove"
            >
              <n-li v-for="ele in list2" :key="ele.name">
                20秒 {{ele.name}}
              </n-li>
            </VueDraggableNext>
          </n-ul>

        </n-grid-item>
      </n-grid>
    </n-card>


    <n-modal
        v-model:show="modalShow"
        :mask-closable="false"
        preset="dialog"
        title="选择语音"
        content="你确认"
        positive-text="确认"
        negative-text="取消"
        @positive-click="addVoice"
    >
      <n-form
          ref="storyFormRef">
        <n-form-item label="引用音频" path="mediaId">
          <n-select
              v-model:value="audioFileId"
              :options="mediaInfoList"
              label-field="name"
              value-field="fileUserId"
              :render-option="mediaInfoSelectRender"
              clearable>
          </n-select>
        </n-form-item>
      </n-form>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import {h,onMounted, ref} from "vue"
//@ts-ignore
import Bus from "@/components/file/box/GlobalUploader/utils/bus"
import {storyController} from "@/api/story/story.api"
import fileFunction from "@/libs/globalFunction/file";
import {mediaController} from "@/api/controller/media/mediaController";
import {whisperController} from "@/api/controller/media/whisperController";
import {NInput, NTag, NTooltip} from "naive-ui";
import {Diff} from "vue-diff";
import {VueDraggableNext} from 'vue-draggable-next'




const audioPlayer = ref(null)
const audioFileId = ref(null)
const audioSrt = ref('')
const importSRTLoading = ref(false)
const story = ref(null)
const videoTextList = ref([])
const audioSRTList = ref([])
const diffModalShow = ref(false)
const oriText = ref('')
const nowText = ref('')
const sentenceList = ref([])
const modalShow = ref(false)
const mediaInfoList = ref([])

const props = defineProps({
  storyId:{
    type: String,
    default: '',
    required: true
  },
  storyCreatorConfig: {
    type: Object,
    default: () => {
      return {}
    }
  }
})


const  list1 = ref([
    ])

const list2 = ref([
  { name: 'Juan', id: 5 },
  { name: 'Edgard', id: 6 },
  { name: 'Johnson', id: 7 },
])

const  list3 = ref([
])

const log = (event:any) => {
  const { moved, added } = event
  if (moved) console.log('moved', moved)
  if (added) console.log('added', added, added.element)
}



const add = () => {
  console.log('add')
}

const replace = () => {
  console.log('replace')
}

const checkMove = (event:any) => {
  console.log('checkMove', event.draggedContext)
  console.log('Future index: ' + event.draggedContext.futureIndex)
}


onMounted(() => {
  getStory()
  getVideoText()
  getMediaList()
})


const getVideoText = async () => {
  await storyController.getVideoText({
    storyId: props.storyId,
    page:  1 ,
    pageSize: 10000
  }).then(res => {
    if (res.code === 200) {
      videoTextList.value = res.data.records
      sentenceList.value = []
      videoTextList.value.forEach((item: any) => {
        const orderNum = item.orderNum
        if (item.sentenceList) {
          item.sentenceList.forEach((itemSecond: any) => {
            sentenceList.value.push({
              orderNum: orderNum,
              xh: itemSecond.orderNum,
              content: itemSecond.content
            })
          })
        }
      })
    }
  })
}

const uploadFile = () => {
  // 获取当前日期格式
  const uploadFileParams = ref({
    filePath: '/创作室/' + props.storyId + '/上传音频/',
    isDir: 0
  })
  // 打开文件选择框
  Bus.emit('openUploader', {
    // 给服务端的额外参数
    params_: uploadFileParams,
    // 上传方式
    uploadWay_: '1',
    callType_: 1
  })
}


// 文件上传成功的回调
Bus.on('fileSuccess', (file: any) => {
  uploadFileSuccess(file)
})


const removeAudioFile = () => {
  audioFileId.value = null
}

const uploadFileSuccess = (file: any) => {
  const query = file.uploader.opts.query
  if (query.filePath.startsWith('/创作室/' + props.storyId + '/上传音频/')) {
    // 新增media记录
    storyController.addExtraAudioFile(props.storyId, file.uniqueIdentifier).then((res: any) => {
      if (res.code === 200) {
        getStory()
      }
    })
  }
}

const getStory = () => {
  storyController.getStoryById(props.storyId).then((res) => {
    if (res.code === 200) {
      story.value = res.data.story
      getText(story.value.extraAudioFileId)
      audioFileId.value = story.value.extraAudioFileId
    }
  })
}

const convert = (secondsstr: number) => {
  const hours = Math.floor(secondsstr / 3600);
  const minutes = Math.floor((secondsstr % 3600) / 60);
  const seconds = Math.floor(secondsstr % 60);
  const milliseconds = (secondsstr.toString().split('.')[1] || '000').padEnd(3, '0');
  // Format as two-digit strings
  const hoursStr = String(hours).padStart(2, '0');
  const minutesStr = String(minutes).padStart(2, '0');
  const secondsStr = String(seconds).padStart(2, '0');
  const millisecondsStr = String(milliseconds).padStart(3, '0');
  // SRT time format: hh:mm:ss,mmm
  return `${hoursStr}:${minutesStr}:${secondsStr},${millisecondsStr}`
}

function isValidSrtLine(line) {
  const regex = /^(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n(.+)\n$/;
  return regex.test(line);
}


const getText = (userFileId: string) => {
  // 查看文本
  whisperController.getText(userFileId).then((res) => {
    if (res.code === 200) {
      audioSRTList.value = res.data
      audioSrt.value = ''
      let index = 1;
      for (let i = 0; i < res.data.length; i++) {
        let start = convert(res.data[i].startTime);
        let end = convert(res.data[i].endTime);
        let text = res.data[i].videoText;
        audioSrt.value += index + '\n';
        audioSrt.value += start + ' --> ' + end + '\n';
        audioSrt.value += text + '\n\n';
        index++;
      }
    }
  })
}



// 从 SRT 文件中提取字幕
function extractSubtitles(srt: string) {
  const subtitles = [];
  const lines = srt.trim().split('\n');
  let index = 0;
  while (index < lines.length) {
    if (lines[index] === '') {
      index++;
      continue;
    }
    const id = parseInt(lines[index++]);
    const time = lines[index++];
    const [startTime, endTime] = time.split(' --> ').map(parseTime);
    const text = [];

    while (index < lines.length && lines[index]) {
      text.push(lines[index++]);
    }
    subtitles.push({id, startTime, endTime, videoText: text.join('\n')});
    index++;
  }
  return subtitles;
}


function parseTime(time: string) {
  const [hours, minutes, seconds] = time.split(':');

  if (seconds === 0) {
    return hours * 3600 + minutes * 60;
  } else {
    const [secondsPart, milliseconds] = seconds.split(',').map(parseFloat);
    return hours * 3600 + minutes * 60 + secondsPart + milliseconds / 1000;
  }
}





const addVoice = () => {
  storyController.addExtraAudioFile(props.storyId, audioFileId.value).then((res: any) => {
    if (res.code === 200) {
      getStory()
    }
  })
}

const getMediaList = () => {
  mediaController.listMediaList({}, {
    page: 1,
    pageSize: 1000
  }).then((res) => {
    if (res.code === 200) {
      mediaInfoList.value = res.data.list
      mediaInfoList.value.forEach((item: any) => {
        item.disabled = true
        if (item.videoToTxtStatus === 'SUCCESS' || item.ocrStatus === 'SUCCESS') {
          item.disabled = false
        }
      })
    }
  })
}

const mediaInfoSelectRender = (info: any) => {
  return h(NTooltip, null, {
    trigger: () => info.node,
    default: () => {
      console.log(info.node)
      if (info.option.disabled) {
        return h(NTag, {type: 'error'}, () => '请将视频/音频转换为文字')
      } else {
        return h(NTag, {type: 'success'}, () => '类型:' + info.option.ext + '     时长:' + formatSeconds(info.option.videoTime / 1000 / 1000))
      }
    }
  })
}


function formatSeconds(seconds) {
  const hour = Math.floor(seconds / 3600);
  seconds = seconds % 3600;
  const minute = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);

  return [
    hour.toString().padStart(2, '0'),
    minute.toString().padStart(2, '0'),
    seconds.toString().padStart(2, '0')
  ].join(':');
}
</script>
